package com.jiedeng.controller;

import com.jiedeng.dao.*;
import com.jiedeng.entity.ProjectCorpDetails;
import com.jiedeng.entity.ProjectDetails;
import com.jiedeng.mapper.ProjectMapper;
import com.jiedeng.model.*;
import com.jiedeng.util.DatetimeUtil;
import org.omg.CORBA.Object;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author zyb
 * @ClassName: ProjectController
 * @Description:
 * @date 2017/5/24 14:03
 */
@RestController
@RequestMapping("/projectManage")
public class ProjectController {

    @Autowired
    private IProjectRepository projectRepository;
    @Autowired
    private ICorpRepository corpRepository;
    @Autowired
    private IProjectCorpRepository projectCorpRepository;
    @Autowired
    private IProjectPersonRepository projectPersonRepository;

    @Autowired
    private IProTypeRepository proTypeRepository;
    @Autowired
    private IPersonRepository personRepository;
    @Autowired
    private IProDegreeRepository proDegreeRepository;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ICorpPostRepository corpPostRepository;
    @Autowired
    private ICorpPropRepository corpPropRepository;

    /**
     * 根据用户查询待审核项目
     *
     * @param checker 人员id
     * @return Project集合
     */
    @RequestMapping(value = "/projectAuditing", method = RequestMethod.GET)
    public List<Project> projectAuditing(String checker) {
        List<Project> projectList = projectRepository.findByStatusAndChecker(4, Long.valueOf(checker));
        if (projectList != null && projectList.size() > 0) {
            return projectList;
        }
        return null;
    }

    /**
     * 根据用户查询待完工项目
     *
     * @param checker 人员id
     * @return Project集合
     */
    @RequestMapping(value = "/projectComplete", method = RequestMethod.GET)
    public List<ProjectDetails> projectComplete(String checker) {
        List<Project> projectList = projectRepository.findByStatusAndChecker(3, Long.valueOf(checker));
        if (projectList != null && projectList.size() > 0) {
            List<ProjectDetails> projectDetailsList = new ArrayList<>();
            for (Project project : projectList) {
                ProjectDetails projectDetails = new ProjectDetails();
                projectDetails.setId(project.getId());
                projectDetails.setCaption(project.getCaption());
                projectDetails.setCap(project.getCap());
                projectDetails.setStime(project.getStime());
                projectDetails.setEtime(project.getEtime());
                projectDetails.setAddtime(project.getAddtime());
                Optional<ProType> proTypeOptional = proTypeRepository.findById((int) project.getProTypeId());
                if (proTypeOptional.isPresent()) {
                    ProType proType = proTypeOptional.get();
                    projectDetails.setProTypeName(proType.getCaption());
                }
                Optional<ProDegree> proDegreeOptional = proDegreeRepository.findById((int) project.getProDegreeId());
                if (proDegreeOptional.isPresent()) {
                    ProDegree proDegree = proDegreeOptional.get();
                    projectDetails.setProDegreeName(proDegree.getCaption());
                }
                Optional<Person> personOptional = personRepository.findById(project.getCreater());
                if (personOptional.isPresent()) {
                    Person createrPerson = personOptional.get();
                    projectDetails.setCreaterName(createrPerson.getName());
                }
                Optional<Person> checkerPersonOptional = personRepository.findById(project.getChecker());
                if (checkerPersonOptional.isPresent()) {
                    Person checkerPerson = checkerPersonOptional.get();
                    projectDetails.setCheckerName(checkerPerson.getName());
                }
                projectDetails.setCheckTime(project.getCheckTime());
                projectDetailsList.add(projectDetails);
            }
            return projectDetailsList;
        }
        return null;
    }

    /**
     * 根据单位性质获取单位
     *
     * @param corpPropId
     * @return
     */
    @RequestMapping(value = "/findCorpListByCorpPropId", method = RequestMethod.GET)
    public List<Corp> findCorpListByCorpPropId(String corpPropId) {
        return corpRepository.findByCorpPropId(Long.valueOf(corpPropId));
    }

    /**
     * 添加项目
     *
     * @param caption 描述
     * @param cap  cap
     * @param projectCode 项目编码
     * @param stime 开始时间
     * @param etime 结束时间
     * @param epsId epsid
     * @param proTypeId 类型
     * @param proDegreeId 类型
     * @param closeTime 关闭时间
     * @param contactInfo 描述
     * @param zoneId zoneid
     * @param memo  描述
     * @param checker 人员
     * @param creater 创建人
     * @param corpPropCorpIds 单位性质-单位id
     * @return rst
     */
    @RequestMapping("addProjectEntity")
    public Rst addProjectEntity(String caption, String cap, String projectCode, String stime, String etime, String epsId, String proTypeId, String proDegreeId, String closeTime, String contactInfo, String zoneId, String memo, String checker, String creater, String corpPropCorpIds) {
        Rst rst = new Rst();
        try {
            Project project = new Project();
            project.setCaption(caption);
            project.setCap(cap);

            project.setStime(DatetimeUtil.formartDate("yyyy-MM-dd HH:mm:ss", stime, 0));
            project.setEtime(DatetimeUtil.formartDate("yyyy-MM-dd HH:mm:ss", etime, 0));

            project.setStatus(4);
            project.setAddtime(new Date());
            project.setEpsId(Long.valueOf(epsId));
            project.setProTypeId(Long.valueOf(proTypeId));
            project.setProDegreeId(Long.valueOf(proDegreeId));
            if (!StringUtils.isEmpty(zoneId)) {
                project.setZoneId(Long.valueOf(zoneId));
            }
            if (!StringUtils.isEmpty(projectCode)) {
                project.setProjectCode(projectCode);
            }
            if (!StringUtils.isEmpty(contactInfo)) {
                project.setContactInfo(contactInfo);
            }
            if (!StringUtils.isEmpty(memo)) {
                project.setMemo(memo);
            }
            project.setChecker(Long.valueOf(checker));
            project.setCreater(Long.valueOf(creater));
            projectRepository.save(project);
            addProjectCorpEntity(corpPropCorpIds, project.getId());
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 添加项目单位
     *
     * @param corpPropCorpIds
     * @param projectId
     */
    public void addProjectCorpEntity(String corpPropCorpIds, long projectId) {
        if (StringUtils.isEmpty(corpPropCorpIds)) {
            return;
        }
        String[] corpPropCorpId = corpPropCorpIds.split(",");
        for (String corpPropCorp : corpPropCorpId) {
            String[] corpPropAndCorp = corpPropCorp.split("-");
            ProjectCorp projectCorp = new ProjectCorp();
            projectCorp.setCorpPropId(Long.valueOf(corpPropAndCorp[0]));
            projectCorp.setCorpId(Long.valueOf(corpPropAndCorp[1]));
            projectCorp.setProjectId(projectId);
            projectCorpRepository.save(projectCorp);
        }
    }

    /**
     * 修改项目状态
     *
     * @param projectId
     * @param status
     * @return
     */
    @RequestMapping("editProjectStatus")
    public Rst editProjectStatus(String projectId, String status) {
        Rst rst = new Rst();
        try {
            Project project = projectRepository.getOne(Long.valueOf(projectId));
            project.setStatus(Integer.valueOf(status));
            if (Integer.valueOf(status) == 2) {
                project.setCloseTime(DatetimeUtil.getNow());
            }
            if (Integer.valueOf(status) == 3) {
                project.setCheckTime(DatetimeUtil.getNow());
            }
            projectRepository.save(project);
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 删除项目
     *
     * @param projectId 项目id
     * @return rst
     */
    @RequestMapping("delProjectById")
    public Rst delProjectById(String projectId) {
        Rst rst = new Rst();
        try {
            //删除项目单位关系表
            List<ProjectCorp> projectCorpList = projectCorpRepository.findByProjectId(Long.valueOf(projectId));
            for (ProjectCorp projectCorp : projectCorpList) {
                projectCorpRepository.delete(projectCorp);
            }
            //项目人员关系表
            List<ProjectPerson> projectPersonList = projectPersonRepository.findByProjectId(Long.valueOf(projectId));
            for (ProjectPerson projectPerson : projectPersonList) {
                projectPersonRepository.delete(projectPerson);
            }
            //删除项目表
            projectRepository.deleteById(Long.valueOf(projectId));
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            e.printStackTrace();
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 根据用户获取项目列表
     *
     * @param personCorpId 用户id
     * @return 项目集合
     */
    @RequestMapping(value = "/getProjectByPerson", method = RequestMethod.GET)
    public List<Project> getProjectByPerson(long personCorpId) {

//        List<ProjectCorp> projectPersonList = projectCorpRepository.findByCorpId(personCorpId);

        List<Project> projectList = projectRepository.findProjectByCorpIdSQL(personCorpId);
        List<Project> projects = new ArrayList<Project>();
        Map<Long, String> checkRepeat = new HashMap<Long, String>();
        for (Project project : projectList) {

            if (project.getStatus() != 3) {
                continue;
            }
            if (!checkRepeat.containsKey(project.getId())) {
                checkRepeat.put(project.getId(), "记录是否存在！");
                projects.add(project);
            }
            //System.out.println(project.getCaption());

        }
      /*  for (ProjectCorp p : projectPersonList) {
            if (p.getProjectId() > 0) {
                Optional<Project> project = projectRepository.findById(p.getProjectId());
                //Project project = projectRepository.getOne(p.getProjectId());
                if (project.isPresent()) {
                    if (project.get().getStatus() != 3) {
                        continue;
                    }
                    if (!checkRepeat.containsKey(project.get().getId())) {
                        checkRepeat.put(project.get().getId(), "记录是否存在！");
                        projects.add(project.get());
                    }
                    //System.out.println(project.getCaption());
                }
            }
        }*/

        return projects;
    }

    /**
     * 根据项目查询单位
     *
     * @param projectId
     * @return
     */
    @RequestMapping("findCorpByProjectId")
    public List<ProjectCorpDetails> findCorpByProjectId(String projectId, String personCorpId) {
        List<ProjectCorpDetails> projectList = new ArrayList<ProjectCorpDetails>();
        try {
            List<ProjectCorp> projectCorpList = projectCorpRepository.findByCorpIdAndProjectId(Long.valueOf(personCorpId), Long.valueOf(projectId));
            if (projectCorpList != null && projectCorpList.size() > 0) {
                ProjectCorp projectCorp = projectCorpList.get(0);
                if (projectCorp.getCorpPropId() == 2) {
                    //项目单位关系表
                    List<ProjectCorpDetails> projectCorpDetailsList = projectMapper.findProjectCorpByProjectId(Long.valueOf(projectId));
                    if (projectCorpDetailsList != null && projectCorpDetailsList.size() > 0) {
                        projectList = projectCorpDetailsList;
                    }
                } else {
                    ProjectCorpDetails projectCorpDetails = new ProjectCorpDetails();
                    Corp corp = corpRepository.getOne(Long.valueOf(personCorpId));
                    projectCorpDetails.setCorpId(corp.getId());
                    projectCorpDetails.setCorpName(corp.getCaption());
                    projectCorpDetails.setId(projectCorp.getId());
                    projectCorpDetails.setCorpPropId(corp.getCorpPropId());
                    projectCorpDetails.setProjectId(Long.valueOf(projectId));
                    CorpProp corpProp = corpPropRepository.getOne(corp.getCorpPropId());
                    if (corpProp != null) {
                        projectCorpDetails.setCorpPropCaption(corpProp.getCaption());
                    }
                    projectList.add(projectCorpDetails);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();

        }
        return projectList;
    }

    /**
     * 根据项目查询单位
     *
     * @param projectId
     * @return
     */
    @RequestMapping("getCorpListByProjectId")
    public List<Corp> getCorpListByProjectId(Long projectId) {
        List<ProjectCorp> projectCorpList = projectCorpRepository.findByProjectId(projectId);
        List<Corp> corpList = new ArrayList<Corp>(10);
        for (ProjectCorp projectCorp : projectCorpList) {
            Corp corp = corpRepository.findAllById(projectCorp.getCorpId());
            corpList.add(corp);
        }
        return corpList;
    }

    /**
     * 根据单位性质获取对应岗位
     *
     * @param corpPropId
     * @return
     */
    @RequestMapping(value = "/findCorpPostByPropId", method = RequestMethod.GET)
    public List<CorpPost> findCorpPost(long corpPropId) {
        long startId = 0;
        long endId = 0;
        //建设管理单位岗位
        if (corpPropId == 2) {
            startId = 9200;
            endId = 9300;
        }
        //监理单位岗位
        if (corpPropId == 4) {
            startId = 9400;
            endId = 9500;
        }
        //施工单位岗位
        if (corpPropId == 5) {
            startId = 9500;
            endId = 9600;
        }
        List<CorpPost> buildCorpPosts = corpPostRepository.findByIdBetween(startId, endId);
        return buildCorpPosts;
    }

    /**
     * 人员调配
     *
     * @param corpId 单位
     * @param postPropPersonIds 岗位-人员
     * @param projectId 项目id
     * @return rst
     */
    @RequestMapping("addPersonAllocation")
    public Rst addPersonAllocation(String corpId, String postPropPersonIds, String projectId) {
        Rst rst = new Rst();
        try {
            projectMapper.deleteProjectPersonByCorpIdAndProjectId(Long.valueOf(corpId), Long.valueOf(projectId));
            String[] postPropIdArray = postPropPersonIds.split("&");
            for (String postPropId : postPropIdArray) {
                String[] postPerSonIdArray = postPropId.split("-");
                long postId = Long.valueOf(postPerSonIdArray[0]);
                String[] personIds = postPerSonIdArray[1].split(",");
                for (String personId : personIds) {
                    ProjectPerson projectPerson = new ProjectPerson();
                    projectPerson.setPostId(postId);
                    projectPerson.setProjectId(Long.valueOf(projectId));
                    projectPerson.setPersonId(Long.valueOf(personId));
                    projectPersonRepository.save(projectPerson);
                }
            }
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            e.printStackTrace();
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 获取岗位人员
     *
     * @param projectId
     * @param postId
     * @return
     */
    @RequestMapping(value = "/getProjectPerson", method = RequestMethod.GET)
    public List<ProjectPerson> getProjectPerson(long projectId, long postId) {
        return projectPersonRepository.findByProjectIdAndPostId(projectId, postId);
    }

    /**
     * 获取单位性质
     *
     * @return
     */
    @RequestMapping(value = "/getCorpProp", method = RequestMethod.GET)
    public List<CorpProp> getCorpProp() {
        return corpPropRepository.findAll();
    }

    /**
     * 获取项目详情
     *
     * @param projectId 项目id
     * @return 项目详情
     */
    @RequestMapping(value = "/getProjectDetailsById", method = RequestMethod.GET)
    public ProjectDetails getProjectDetailsById(long projectId) {
        List<ProjectDetails> projectDetailsList = projectMapper.findProjectDetailsById(projectId);
        ProjectDetails projectDetails = new ProjectDetails();
        if (projectDetailsList != null && projectDetailsList.size() > 0) {
            projectDetails = projectDetailsList.get(0);
        }
        List<Map<String, String>> corpPropCorpList = projectMapper.findCorpPropAndCorpByProjectId(projectId);
        projectDetails.setCorpPropCorpList(corpPropCorpList);
        return projectDetails;
    }

    @RequestMapping(value = "/persons", method = RequestMethod.GET)
    public List<Person> corpPersonList(long corpId) {
        ///原方法
       /* List<Person> personList=new ArrayList<Person>();
        List<Person> persons=personRepository.findByCorpId(corpId);
        for (Person person : persons) {
            if(!person.isLock()){
                personList.add(person);}
        }
        return personList;*/
        return personRepository.findByCorpIdAndIsLock(corpId, false);
    }

    @RequestMapping(value = "/all_person", method = RequestMethod.GET)
    public List<Person> findAllPerson() {
        ///原方法
        /*List<Person> personList=new ArrayList<Person>();
        List<Person> persons=personRepository.findAll();
        for (Person person : persons) {
            if(!person.isLock()){
                personList.add(person);}
        }
        return personList;*/
        return personRepository.findByIsLock(false);
    }
}